
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.DictExamZoneDto;
import com.rt.schedulebase.dto.DictUserRoleDto;
import com.rt.schedulebase.dto.DictUsersDto;
import com.rt.schedulebase.entity.DictExamZone;
import com.rt.schedulebase.entity.DictUsers;
import com.rt.schedulebase.entity.commonentity.PageResultUtil;
import com.rt.schedulebase.mapper.DictUsersMapper;
import com.rt.schedulenew.api.IDictExamZoneService;
import com.rt.schedulenew.api.IDictUserRoleService;
import com.rt.schedulenew.api.IDictUsersService;
import com.rt.schedulenew.utils.global.ErrorCode;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class DictUsersServiceImpl extends ServiceImpl<DictUsersMapper, DictUsers> implements IDictUsersService {
    @Autowired
    private IDictUserRoleService dictUserRoleService;
    @Autowired
    private IDictExamZoneService dictExamZoneService;

    @Override
    public JsonResult insertUser(DictUsers dictUsers) {
        QueryWrapper<DictUsers> qw = new QueryWrapper<>();
        ((qw.eq("STAFF_NO", dictUsers.getStaffNo())).or())
                .eq("USER_ID", dictUsers.getUserId().toUpperCase());

        int count = baseMapper.selectCount(qw);
        if (count > 0) {
            return JsonResultUtil.failure("新增失败：员工号或用户名已存在");
        }
        if (dictUsers.getStaffNo() != null && dictUsers.getStaffNo().length() > 10) {
            return JsonResultUtil.failure("新增失败：员工ID超长！");
        }
        if (dictUsers.getName() != null && dictUsers.getName().length() > 25) {
            return JsonResultUtil.failure("新增失败：姓名超长！");
        }
        if (dictUsers.getUserId() != null && dictUsers.getUserId().length() > 8) {
            return JsonResultUtil.failure("新增失败：用户名超长！");
        }
        if (dictUsers.getAlias() != null && dictUsers.getAlias().length() > 8) {
            return JsonResultUtil.failure("新增失败：别名超长！");
        }
        if (dictUsers.getInputCode() != null && dictUsers.getInputCode().length() > 8) {
            return JsonResultUtil.failure("新增失败：输入码超长！");
        }
        if (dictUsers.getStaffNo() != null && dictUsers.getStaffNo().length() > 8) {
            return JsonResultUtil.failure("新增失败：排序号超长！");
        }

        Pattern pattern = Pattern.compile("[0-9]*");
        if (dictUsers.getInputCode() != null && dictUsers.getInputCode().length() > 0) {
            if (!pattern.matcher(dictUsers.getInputCode()).matches()) {
                return JsonResultUtil.failure("新增失败：输入码需为纯数字");
            }
        }
        if (dictUsers.getStaffNo() != null && dictUsers.getStaffNo().length() > 0) {
            if (!pattern.matcher(dictUsers.getStaffNo()).matches()) {
                return JsonResultUtil.failure("新增失败：员工ID需为纯数字");
            }
        }

        dictUsers.setCreateDate(DateUtil.getCurrDateStr());
        dictUsers.setPasswordDate(dictUsers.getCreateDate());

        if (StringUtils.isNotBlank(dictUsers.getUserId())) {
            dictUsers.setUserId(dictUsers.getUserId().toUpperCase());
        }
        if (StringUtils.isNotBlank(dictUsers.getPassword())) {
            dictUsers.setPassword(dictUsers.getPassword().toUpperCase());
        }
        boolean bool = retBool(baseMapper.insert(dictUsers));
        if (bool) {
            return JsonResultUtil.success();
        }
        return JsonResultUtil.failure();
    }


    @Override
    public List<DictUsers> getList(DictUsersDto dto) {
        Map<String, Object> map = new HashMap<>();
        map.put("DEPT_CODE", dto.getDeptCode());
        map.put("STAFF_NO", dto.getStaffNo());
        if (StringUtils.isNotBlank(dto.getUserId())) {
            map.put("USER_ID", dto.getUserId().toUpperCase());
        }
        map.put("STAFF_TYPE", dto.getStaffType());
        map.put("PASSWORD", dto.getPassword());
        QueryWrapper<DictUsers> qw = new QueryWrapper<>();
        qw.allEq(map, false);
        List<DictUsers> list = baseMapper.selectList(qw);
        return list;
    }

    @Override
    public List<DictUsers> getListAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public boolean delete(DictUsers dictUsers) {
        Map<String, Object> map = new HashMap<>();
        map.put("USER_ID", dictUsers.getUserId().toUpperCase());

        UpdateWrapper<DictUsers> uw = new UpdateWrapper<>();
        uw.allEq(map);
        return retBool(baseMapper.delete(uw));
    }

    @Override
    public boolean update(DictUsersDto dictUsersDto) {
        if (dictUsersDto.getOldPassword() != null) {
            dictUsersDto.setOldPassword(dictUsersDto.getOldPassword().toUpperCase());
        }
        if (dictUsersDto.getPassword() != null) {
            dictUsersDto.setPassword(dictUsersDto.getPassword().toUpperCase());
        }
        if (StringUtils.isNotBlank(dictUsersDto.getUserId())) {
            dictUsersDto.setUserId(dictUsersDto.getUserId().toUpperCase());
        }

        // 旧密码和新密码都不为空切不相同，则更新密码更新日期
        if (StringUtils.isNotBlank(dictUsersDto.getOldPassword())
                && StringUtils.isNotBlank(dictUsersDto.getPassword())
                && !dictUsersDto.getOldPassword().equals(dictUsersDto.getPassword())) {
            dictUsersDto.setPasswordDate(DateUtil.getCurrDateStr());
        }

        UpdateWrapper<DictUsers> uw = new UpdateWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("USER_ID", dictUsersDto.getUserId());
        uw.allEq(map);
        return retBool(baseMapper.update(dictUsersDto, uw));
    }

    @Override
    public boolean setPrinter(DictUsersDto user) {
        UpdateWrapper<DictUsers> uw = new UpdateWrapper<>();
        uw.eq("USER_ID", user.getUserId());
        uw.set("PRINTER_NAME", user.getPrinterName());
        return retBool(baseMapper.update(null, uw));
    }

    @Override
    public DictUsers getInfo(DictUsersDto dto) {
        QueryWrapper<DictUsers> qw = new QueryWrapper();
        Map<String, Object> map = new HashMap<>();
        map.put("STAFF_NO", dto.getStaffNo());
        if (StringUtils.isNotBlank(dto.getUserId())) {
            map.put("USER_ID", dto.getUserId().toUpperCase());
        }
        map.put("DEPT_CODE", dto.getDeptCode());
        map.put("NAME", dto.getName());
        qw.allEq(map, false);
        return baseMapper.selectOne(qw);
    }

    @Override
    public DictUsersDto getUserInfo(String userId) {
        DictUsersDto dictUsersDto = new DictUsersDto();
        dictUsersDto.setUserId(userId.toUpperCase());
        List<DictUsersDto> dictUsersDtoList = baseMapper.getUserList(dictUsersDto);
        return (!CollectionUtils.isEmpty(dictUsersDtoList)) ? dictUsersDtoList.get(0) : null;
    }

    @Override
    public JsonResult getUserLogin(String userId) {
        userId = userId.toUpperCase();
        DictUserRoleDto dictUserRoleDto = new DictUserRoleDto();
        dictUserRoleDto.setUserId(userId);
        List<DictUserRoleDto> lsDictUserRole = dictUserRoleService.getUserRoleList(dictUserRoleDto);
        if (lsDictUserRole.size() == 0) {
            return JsonResultUtil.failure("用户暂未分配角色");
        }
        DictUsersDto dictUsersDto = new DictUsersDto();
        dictUsersDto.setUserId(userId);
        List<String> lsFunction = baseMapper.getUserFunctionList(dictUsersDto);
        if (lsFunction.size() == 0) {
            return JsonResultUtil.failure("用户暂未分配功能权限");
        }
        DictUsersDto dto = new DictUsersDto();
        dto.setUserId(userId);
        DictUsersDto userInfo = baseMapper.getUserList(dto).get(0);
        if (userInfo.getExpireDate() != null && DateUtil.getCurrDateStr().compareTo(userInfo.getExpireDate()) > 0) {
            return JsonResultUtil.failure(ErrorCode.UNKNOWN_ERROR.getKey(), "用户登录权限已过期");
        }
        dto.setDeptCode(userInfo.getDeptCode());
        dto.setHospitalName(userInfo.getHospitalName());
        dto.setHospitalCode(userInfo.getHospitalCode());
        dto.setDeptName(userInfo.getDeptName());
        dto.setName(userInfo.getName());
        dto.setStaffNo(userInfo.getStaffNo());
        dto.setPassword(userInfo.getPassword());
        dto.setPrinterName(userInfo.getPrinterName());
        DictUsersDto ward = baseMapper.getUserWard(dto);
        if (ward != null) {
            dto.setWardCode(ward.getWardCode());
            dto.setWardName(ward.getWardName());
        }
        List<String> roleNameList = new ArrayList<String>();
        for (DictUserRoleDto dictUserRole : lsDictUserRole) {
            if (dictUserRole != null) {
                roleNameList.add(dictUserRole.getRoleName());
            }
        }
        dto.setRoleNames(roleNameList);
        dto.setFunctions(lsFunction);
        Map<String, String> functionClassMap = new HashMap<>();
        List<String> examClassList = baseMapper.getUserExamClassList(dto);
        for (String examClass : examClassList) {
            dto.setExamClass(examClass);
            List<String> funIdList = baseMapper.getUserFunctionList(dto);
            String funId = null;
            if (!funIdList.isEmpty()) {
                funId = StringUtils.join(funIdList, ",");
            }
            functionClassMap.put(dto.getExamClass(), funId);
        }
        dto.setFunctionClass(functionClassMap);
        dto.setExamClassList(examClassList);
        List<String> zoneNameList = new ArrayList<>();
        DictExamZoneDto dctExamZoneDto = new DictExamZoneDto();
        dctExamZoneDto.setExamClass(StringUtils.join(examClassList, ","));
        List<DictExamZone> lsZone = dictExamZoneService.getList(dctExamZoneDto);
        for (DictExamZone dictExamZone : lsZone) {
            zoneNameList.add(dictExamZone.getZoneName());
        }
        dto.setZoneNameList(zoneNameList);
        return JsonResultUtil.success(dto);
    }

    @Override
    public List<DictUsersDto> getUserList(DictUsersDto dto) {
        return baseMapper.getUserList(dto);
    }

    @Override
    public JsonResult getListPage(DictUsersDto dto) {
        if (StringUtils.isNotBlank(dto.getName())) {
            dto.setName(dto.getName().replace(" ", ""));
        }
        Page<DictUsersDto> page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<DictUsersDto> list = baseMapper.getUserList(dto);
        JsonResult jsonResult = PageResultUtil.success(ErrorCode.SUCCESS.getValue(), list, page);
        return jsonResult;
    }
}
